import 'dart:convert';

import 'package:dimi_connect/bean/login_entity.dart';
import 'package:dimi_connect/http/Api.dart';
import 'package:dimi_connect/util/view_creator.dart';
import 'package:dimi_connect/view/loading_dialog.dart';
import 'package:dimi_connect/view/login_code_view.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class Login extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return FormTestRoute();
  }
}

class FormTestRoute extends StatefulWidget {
  @override
  _FormTestRouteState createState() => new _FormTestRouteState();
}

class _FormTestRouteState extends State<FormTestRoute> {
  TextEditingController _unameController = TextEditingController();
  TextEditingController _pwdController = TextEditingController();
  GlobalKey<FormFieldState<String>> _phoneKey =
      GlobalKey<FormFieldState<String>>();

  GlobalKey _formKey = GlobalKey<FormState>();

  static bool isPhone(String str) {
    return RegExp('^[1]([3-9])[0-9]{9}\$').hasMatch(str);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          leading: IconButton(
              onPressed: () {
                Navigator.pop(context);
              },
              icon: Icon(Icons.arrow_back)),
          title: Text("登录"),
        ),
        body: Builder(
            builder: (context) => GestureDetector(
                behavior: HitTestBehavior.translucent,
                onTap: () {
                  // 触摸收起键盘
                  FocusScope.of(context).unfocus();
                },
                child: Center(
                    child: Form(
                        key: _formKey,
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Padding(
                                padding: EdgeInsets.all(15),
                                child: TextFormField(
                                    autofocus: true,
                                    key: _phoneKey,
                                    controller: _unameController,
                                    decoration: ViewCreator.createDecoration(
                                        "账号", "注册Dimi的手机号"),
                                    validator: (v) {
                                      if (isPhone(v.trim())) {
                                        return null;
                                      } else {
                                        return "输入的不是一个手机号码";
                                      }
                                    })),
                            Padding(
                                padding: EdgeInsets.all(15),
                                child: Center(
                                  child: Stack(
                                      alignment: Alignment.centerLeft,
                                      children: <Widget>[
                                        Align(
                                            alignment: Alignment.centerLeft,
                                            child: TextFormField(
                                                autofocus: true,
                                                maxLength: 6,
                                                controller: _pwdController,
                                                decoration: ViewCreator
                                                    .createDecoration(
                                                        "验证码", "收到的验证码"),
                                                validator: (v) {
                                                  return v.trim().length == 6
                                                      ? null
                                                      : "验证码应为6位数字";
                                                })),
                                        Align(
                                            alignment: Alignment.centerRight,
                                            child: Padding(
                                              padding: EdgeInsets.only(
                                                  right: 10, bottom: 20),
                                              child: LoginFormCode(
                                                  onTapCallback: () {
                                                if ((_phoneKey.currentState)
                                                    .validate()) {
                                                  FocusScope.of(context)
                                                      .unfocus();
                                                  return sendSms(context,
                                                      _unameController.text);
                                                } else
                                                  return false;
                                              }),
                                            ))
                                      ]),
                                )),
                            MaterialButton(
                                color: Colors.blue,
                                highlightColor: Colors.blue[700],
                                colorBrightness: Brightness.dark,
                                textColor: Colors.white,
                                splashColor: Colors.grey,
                                child: Text("登录"),
                                onPressed: () {
                                  if ((_formKey.currentState as FormState)
                                      .validate()) {
                                    login(context, _unameController.text,
                                        _pwdController.text);
                                  }
                                })
                          ],
                        ))))));
  }

  void showSnack(BuildContext context, String text) {
    SnackBar snackBar = SnackBar(content: Text(text));
    Scaffold.of(context).showSnackBar(snackBar);
  }

  bool sendSms(BuildContext context, String phone) {
    Api.sendSms(phone, success: (v) {
      showSnack(context, v);
    }, error: (e) {
      showSnack(context, "验证码发送失败:" + e);
    });

    return true;
  }

  void login(BuildContext context, String phone, String code) {
    LoadingDialog.showLoading(context, "正在登录账号");
    Api.login(phone, code, success: (LoginData entity) {
      Navigator.pop(context);
      entity.phone = phone;
      Navigator.pop(context, jsonEncode(entity.toJson()));
    }, error: (e) {
      Navigator.pop(context);
      showSnack(context, "登录失败:" + e);
    });
  }
}
